package Demo79;

public class Main {
}
class Solution {
    public static boolean exist(char[][] board, String word) {
        for(int i = 0; i < board.length;i++) {
            for(int j = 0; j < board[0].length;j++) {
                if(f1(board,word, i, j, 0)) {
                    return true;
                }
            }
        }


        return false;
    }

    public static boolean f1(char[][] board, String word, int i, int j, int pos) {
        if (i < 0 || i == board.length || j < 0 || j == board[0].length) {
            return false;
        }
        if(pos==word.length()) {
            return false;
        }
        if(board[i][j]==word.charAt(pos)) {
            return f1(board, word, i+1, j, pos+1)||
                    f1(board, word, i, j+1, pos+1)||
                    f1(board, word, i-1, j, pos+1)||
                    f1(board, word, i, j-1, pos+1);
        }

        return false;
    }
}